package com.dk.service.order;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.dk.mapper.address.TbAddressMapper;
import com.dk.mapper.address.TbOrderItemMapper;
import com.dk.mapper.order.TbOrderMapper;
import com.dk.mapper.pay.TbPayLogMapper;
import com.dk.pojo.Image;
import com.dk.pojo.address.TbAddress;
import com.dk.pojo.order.*;
import com.dk.pojo.pay.TbPayLog;
import com.dk.pojo.user.TbUser;
import com.dk.redis.CartRedis;
import com.dk.service.cart.OrderCart;
import com.dk.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Component
public class OrderServiceImpl implements OrderService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private TbOrderMapper orderMapper;
    @Resource
    private TbOrderItemMapper orderItemMapper;

    @Resource
    private TbPayLogMapper payLogMapper;
    @Resource
    private TbAddressMapper addressMapper;

    @Override
    public Integer setOrderStatus(String out_trade_no,String status) {
        long parseLong = Long.parseLong(out_trade_no);
        TbOrderExample orderExample = new TbOrderExample();
        TbOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andOrderMotherEqualTo(parseLong);
        List<TbOrder> orderList = orderMapper.selectByExample(orderExample);
        int i = 0;
        for (TbOrder order : orderList) {
            order.setStatus(status);
            i = orderMapper.updateByPrimaryKeySelective(order);
        }
        return i;
    }

    @Transactional
    @Override
    public Integer addOrder(TbUser user, Long addressId, String payType, Double price, long orderMother) {
        List<Cart> cartList = (List<Cart>) redisTemplate.opsForHash().get(CartRedis.CART_LIST, user.getUsername());
        System.out.println(cartList);
        TbAddress address = addressMapper.selectByPrimaryKey(addressId);
        for (Cart cart : cartList) {
            TbOrder order = new TbOrder();
            IdWorker idWorker = new IdWorker();
            long id = idWorker.nextId();
            order.setOrderId(id);
            order.setPayment(new BigDecimal(price));
            order.setPaymentType(payType);
            order.setStatus("1");
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            order.setUserId(user.getId().toString());
            order.setReceiverAreaName(address.getAddress());
            order.setReceiverMobile(address.getMobile());
            order.setReceiver(address.getContact());
            order.setInvoiceType("1");
            order.setSourceType("2");
            order.setSellerId(cart.getSellerId());
            order.setOrderMother(orderMother);
            int i = orderMapper.insertSelective(order);
            List<TbOrderItem> orderItemList = cart.getOrderItemList();
            for (TbOrderItem orderItem : orderItemList) {
                orderItem.setOrderId(id);
                String picPath = orderItem.getPicPath();
                List<Image> images = JSONObject.parseArray(picPath, Image.class);
                String image = images.get(0).getImage();
                orderItem.setPicPath(image);
                int j = orderItemMapper.insertSelective(orderItem);
            }
        }
        redisTemplate.opsForHash().delete(CartRedis.CART_LIST,user.getUsername());
        return 0;
    }

    @Transactional
    @Override
    public Integer saveOrder(TbUser user, Long addressId, String payType, Double price, long orderMother) {


        return 0;
    }

    @Override
    public  List<OrderCart> getOrderByUserId(Long userId) {
        List<OrderCart> orderCartList = new ArrayList<>();
        TbOrderExample orderExample = new TbOrderExample();
        TbOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andUserIdEqualTo(userId.toString());
        List<TbOrder> orderList = orderMapper.selectByExample(orderExample);
        orderCartList = addSouce(orderCartList,orderList);
        return orderCartList ;
    }

    @Override
    public List<OrderCart> getOrderByUserIdAndStatus(Long userId, String status) {
        List<OrderCart> orderCartList = new ArrayList<>();
        TbOrderExample orderExample = new TbOrderExample();
        TbOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andUserIdEqualTo(userId.toString());
        criteria.andStatusEqualTo(status);
        List<TbOrder> orderList = orderMapper.selectByExample(orderExample);
        orderCartList = addSouce(orderCartList,orderList);
        return orderCartList;
    }

    private List<OrderCart> addSouce(List<OrderCart> orderCartList,List<TbOrder> orderList) {
        for (TbOrder order : orderList) {
            OrderCart orderCart = new OrderCart();
            order.setOrderIdString(order.getOrderId().toString());
            order.setOrderMotherString(order.getOrderMother().toString());
            orderCart.setTbOrder(order);
            TbOrderItemExample orderItemExample = new TbOrderItemExample();
            TbOrderItemExample.Criteria exampleCriteria = orderItemExample.createCriteria();
            exampleCriteria.andOrderIdEqualTo(order.getOrderId());
            List<TbOrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);
            for (TbOrderItem orderItem : orderItemList) {
                if (orderCart.getOrderItemList() == null) {
                    List<TbOrderItem> tbOrderItemList = new ArrayList<>();
                    tbOrderItemList.add(orderItem);
                    orderCart.setOrderItemList(tbOrderItemList);
                } else {
                    orderCart.getOrderItemList().add(orderItem);
                }
            }
            orderCartList.add(orderCart);
        }
        return orderCartList;
    }

    @Override
    public int savePayLog(TbPayLog payLog) {
        TbOrderExample example = new TbOrderExample();
        TbOrderExample.Criteria criteria = example.createCriteria();
        criteria.andOrderMotherEqualTo(Long.parseLong(payLog.getOutTradeNo()));
        List<TbOrder> orderList = orderMapper.selectByExample(example);
        List<Long> list = new ArrayList<>();
        for (TbOrder order : orderList) {
            list.add(order.getOrderId());
        }
        String jsonString = JSONObject.toJSONString(list);
        payLog.setOrderList(jsonString);
        payLog.setTradeState("1");
        return payLogMapper.insertSelective(payLog);
    }

    @Override
    public List<TbOrderItem> getOrderItemListByOrderMother(String out_trade_no) {
        TbOrderExample example = new TbOrderExample();
        TbOrderExample.Criteria criteria = example.createCriteria();
        criteria.andOrderMotherEqualTo(Long.parseLong(out_trade_no));
        List<TbOrder> orderList = orderMapper.selectByExample(example);
        List<TbOrderItem> list = new ArrayList<>();
        for (TbOrder order : orderList) {
            TbOrderItemExample orderItemExample = new TbOrderItemExample();
            TbOrderItemExample.Criteria exampleCriteria = orderItemExample.createCriteria();
            exampleCriteria.andOrderIdEqualTo(order.getOrderId());
            List<TbOrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);
            for (TbOrderItem orderItem : orderItemList) {
                list.add(orderItem);
            }
        }
        return list;
    }

    @Override
    public TbPayLog findPayLogById(String out_trade_no) {
        return payLogMapper.selectByPrimaryKey(out_trade_no);
    }

    @Override
    public int setPaylog(String out_trade_no, String trade_no) {
        TbPayLog payLog = payLogMapper.selectByPrimaryKey(out_trade_no);
        payLog.setTransactionId(trade_no);
        payLog.setTradeState("2");
        return payLogMapper.updateByPrimaryKeySelective(payLog);
    }

    @Override
    public int updateOrderStatusByOrderId(Long orderId) {
        TbOrder order = orderMapper.selectByPrimaryKey(orderId);
        order.setStatus("7");
        return orderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public List<TbOrder> findOrderByUserId(Long userId) {
        TbOrderExample orderExample = new TbOrderExample();
        TbOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andUserIdEqualTo(String.valueOf(userId));
        return orderMapper.selectByExample(orderExample);
    }
}
